package cn.chiship.framework.business.biz.business.service.impl;

import cn.chiship.framework.business.biz.business.entity.BusinessForm;
import cn.chiship.framework.business.biz.business.entity.BusinessFormExample;
import cn.chiship.framework.business.biz.business.mapper.BusinessFormMapper;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.business.biz.business.mapper.BusinessFormValueMapper;
import cn.chiship.framework.business.biz.business.entity.BusinessFormValue;
import cn.chiship.framework.business.biz.business.entity.BusinessFormValueExample;
import cn.chiship.framework.business.biz.business.service.BusinessFormValueService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提交的表单数据业务接口实现层
 * 2022/8/19
 *
 * @author lijian
 */
@Service
public class BusinessFormValueServiceImpl extends BaseServiceImpl<BusinessFormValue, BusinessFormValueExample> implements BusinessFormValueService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BusinessFormValueServiceImpl.class);

    @Resource
    BusinessFormValueMapper businessFormValueMapper;

    @Resource
    BusinessFormMapper businessFormMapper;

    @Override
    public BaseResult selectDetailsByPrimaryKey(Object id) {
        BusinessFormValueExample businessFormValueExample = new BusinessFormValueExample();
        businessFormValueExample.createCriteria().andIdEqualTo(id.toString());
        List<BusinessFormValue> workflowFormValues = businessFormValueMapper.selectByExampleWithBLOBs(businessFormValueExample);
        if (workflowFormValues.isEmpty()) {
            return BaseResult.error("暂无工单数据");
        }
        BusinessFormValue businessFormValue = workflowFormValues.get(0);


        BusinessFormExample businessFormExample = new BusinessFormExample();
        businessFormExample.createCriteria().andIdEqualTo(businessFormValue.getFormId());
        List<BusinessForm> businessForms = businessFormMapper.selectByExampleWithBLOBs(businessFormExample);
        if (businessForms.isEmpty()) {
            return BaseResult.ok();
        }
        BusinessForm workflowForm = businessForms.get(0);
        if (StringUtil.isNullOrEmpty(workflowForm.getFormContent())) {
            return BaseResult.error("表单数据缺失");
        }
        Map<String, Object> map = new HashMap(7);
        JSONObject json = JSON.parseObject(JSON.toJSONString(businessFormValue));
        json.put("formName", workflowForm.getName());
        map.put("value", json);
        map.put("form", workflowForm.getFormContent());
        return BaseResult.ok(map);

    }
}
